package com.leonzx.base.service.file;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectResult;
import com.leonzx.base.service.BaseService;
import com.leonzx.base.utils.OSSConstants;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

import static com.leonzx.base.utils.OSSConstants.bucketName;

/**
 * @Author:梁亮
 * @Description:
 * @Date: 2018/7/12 12:24
 */
public class OSSFileUploadService extends BaseService implements FileUploadService {

    private OSSClient ossClient = new OSSClient(OSSConstants.endpoint, OSSConstants.accessKeyId, OSSConstants.accessKeySecret);

    @Override
    public String upload(InputStream inputStream, String key) {
        try {
            PutObjectResult por = ossClient.putObject(bucketName, key.replaceAll("\\\\", "/"), inputStream);
        } catch (Exception e) {
            logger.error("文件上传到OSS失败", e);
        }
        return key;
    }

    @Override
    public String upload(MultipartFile file, String key) {
        InputStream is;
        try {
            is = file.getInputStream();
            upload(is, key);
        } catch (IOException e) {
            logger.error("文件上传到OSS失败", e);
        }
        return key;
    }

    @Override
    public InputStream download(String key) {
        OSSObject object = ossClient.getObject(bucketName, key.replaceAll("\\\\", "/"));
        BufferedInputStream input = new BufferedInputStream(object.getObjectContent());
        return input;
    }

    @Override
    public boolean delete(String key) {
        try {
            ossClient.deleteObject(bucketName, key.replaceAll("\\\\", "/"));
            return true;
        } catch (Exception e) {
            logger.error("OSS上删除文件失败", e);
        }
        return false;
    }

    @Override
    public String getUrlByKey(String key) {
        String url = "http://" + OSSConstants.bucketName + "." + OSSConstants.endpoint + "/" + key ;
        return url;
    }
}
